# -*- coding: UTF-8 -*-

from django import template
from django.conf import settings
from django.views.decorators.cache import cache_page

register = template.Library()

@register.tag(name="get_delicious_links")
def do_delicious_links(parser, token):
    """
    Get the last del.icio.us entries for the configured user in
    DELIGIOUS_USER settings.

    Caches the result for 6 hours.

    {% get_delicious_lings as links%}

    Delicious tags is based on http://www.djangosnippets.org/snippets/819/
    """
    bits = token.contents.split()
    if len(bits) == 3 and bits[1] == 'as':
        return DeliciousObject(bits[2])
    else:
        return template.TemplateSyntaxError, "Invalid sytax: use get_delicious_links as variable_name"
do_delicious_links = cache_page(do_delicious_links, 21600)

class DeliciousObject(template.Node):
    def __init__(self, context_variable):
        self.context_variable = context_variable

    def render(self, context):
        try:
            import feedparser
            d = feedparser.parse('http://del.icio.us/rss/%s'% settings.DELICIOUS_USER)
            delicious=[]
            for entry in d['entries'][:min(8,len(d['entries']))]:
                title=str(entry['title'].encode('ascii', 'xmlcharrefreplace'))
                delicious.append({'title':title,'link':str(entry['links'][0]['href'])})
        except:
            delicious=[]
        context[self.context_variable] = delicious
        return ""

def to_limit(value, arg):
    """Limits the number of characters of a string to the num
    passed as argument adding three dots
        Syntax: {{variable|to_limit:"number"}}

    where:
        variable is whatever wich has a string representation
        number: is the maximum lenght of the string
    """
    arg = int(arg)
    value=str(value)
    if arg < 4:
        raise template.TemplateSyntaxError, "argument must be bigger than 4 for the limit tag"
    if len(value) > arg:
        return "%s ..." % value[:arg-4]
    else:
        return value

register.filter('to_limit', to_limit)